﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Model;
using BLL;
using System.IO;
using ServiceCenterApp.Helper;
using System.Drawing.Imaging;
using System.Net.Sockets;

namespace ServiceCenterApp
{
    public partial class FormProductList : DevExpress.XtraEditors.XtraForm, IChildForm
    {
        ProductBLL productBLL = new ProductBLL();
        CategoryBLL categoryBLL = new CategoryBLL();
        KeyBLL keyBLL = new KeyBLL();

        List<ProductListView> list = new List<ProductListView>();
        List<Category> categoryList = new List<Category>();
        List<Key> keyList = new List<Key>();

        public FormProductList()
        {
            InitializeComponent();
        }

        private void FormProductList_Load(object sender, EventArgs e)
        {
            WinformHelper.BindRepository(repositoryCategoryEditor, categoryList, "Name", "ID");
            WinformHelper.BindRepository(repositoryKeyEditor, keyList, "Name", "ID");
            LoadData();
        }

        private void LoadData()
        {
            categoryList.Clear();
            categoryList.AddRange(categoryBLL.GetAllCategory());
            this.repositoryCategoryEditor.DataSource = categoryList;
            keyList.Clear();
            keyList.AddRange(keyBLL.GetAllKeys());
            this.repositoryKeyEditor.DataSource = keyList;

            this.productListViewBindingSource.DataSource = null;
            list.Clear();

            var plist = productBLL.GetAllProduct();
            plist.ForEach(x =>
            {
                try
                {
                    ProductListView view = new ProductListView { ID = x.ID, Name = x.Name, Price = x.Price, IndexImage = x.IndexImage, Summary = x.Summary, Detail = x.Detail };
                    view.CategoryList = categoryBLL.GetCategoryIDByPID(x.ID);
                    view.KeyList = productBLL.GetKeyIDByPID(x.ID);
                    if (!string.IsNullOrEmpty(view.IndexImage))
                    {
                        try
                        {
                            using (Image image = Image.FromFile(AppHelper.ImageRootPath + view.IndexImage))
                            {
                                if (image != null)
                                {
                                    using (MemoryStream stream = new MemoryStream())
                                    {
                                        image.Save(stream, ImageFormat.Jpeg);
                                        view.IndexImageArray = stream.GetBuffer();
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Program.MainWindow.ShowMessage("产品" + x.Name + "的图片文件打开出错：" + ex.Message);
                        }
                    }
                    view.ImageChanged = false;
                    list.Add(view);
                }
                catch (Exception ex)
                {
                    Program.ShowError(ex);
                }
            });
            this.productListViewBindingSource.DataSource = list;
        }

        public void Save()
        {
            try
            {
                Program.MainWindow.ShowMessage("开始保存数据...");
                list.ForEach(x =>
                {
                    if (x.ImageChanged && x.IndexImageArray != null)
                    {
                        x.IndexImage = Guid.NewGuid().ToString() + ".jpg";
                    }
                });
                productBLL.Save(list.Where(x => !string.IsNullOrEmpty(x.Name)).ToList());
                SaveImage();
                Program.MainWindow.ShowMessage("数据保存完成.");
            }
            catch (Exception ex)
            {
                Program.ShowError(ex);
            }
        }

        public void Delete()
        {
            try
            {
                Program.MainWindow.ShowMessage("开始删除数据...");
                var deletedList = list.Where(x => x.Selected).ToList();
                productBLL.Delete(deletedList);
                deletedList.ForEach(x =>
                {
                    if (!string.IsNullOrEmpty(x.IndexImage))
                    {
                        try
                        {
                            File.Delete(AppHelper.ImageRootPath + x.IndexImage);
                        }
                        catch (Exception ex)
                        {
                            Program.MainWindow.ShowMessage("删除图片文件" + AppHelper.ImageRootPath + x.IndexImage + "失败：" + ex.Message);
                        }
                    }
                });

                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].Selected)
                    {
                        list.RemoveAt(i); i--;
                    }
                }
                Program.MainWindow.ShowMessage("数据删除完成.");
            }
            catch (Exception ex)
            {
                Program.ShowError(ex);
            }
        }

        public void RefreshData()
        {
            LoadData();
        }

        private void SaveImage()
        {
            list.ForEach(x =>
            {
                if (x.ImageChanged && !string.IsNullOrEmpty(x.IndexImage) && x.IndexImageArray != null)
                {
                    using (MemoryStream stream = new MemoryStream(x.IndexImageArray))
                    {
                        using (Image image = Image.FromStream(stream))
                        {

                            using (FileStream fileStream = new FileStream(AppHelper.ImageRootPath + x.IndexImage, FileMode.Create))
                            {
                                image.Save(fileStream, ImageFormat.Jpeg);
                                x.ImageChanged = false;
                            }
                        }
                    }
                }
            });
        }

        private void repositoryItemPictureEdit1_LoadCompleted(object sender, EventArgs e)
        {

        }

        private void repositoryItemPictureEdit1_EditValueChanged(object sender, EventArgs e)
        {

        }

        //如果图片宽度大于设定的宽度则缩小
        private void repositoryItemPictureEdit1_ParseEditValue(object sender, DevExpress.XtraEditors.Controls.ConvertEditValueEventArgs e)
        {
            if (e.Value == null)
            {
                return;
            }

            Byte[] array = e.Value as Byte[];
            using (MemoryStream stream = new MemoryStream(array))
            {
                using (Image image = Image.FromStream(stream))
                {
                    if (image.Width > AppHelper.ThumbnailWidth)
                    {
                        using (Image imageNew = image.GetThumbnailImage(AppHelper.ThumbnailWidth, AppHelper.ThumbnailHeight, new Image.GetThumbnailImageAbort(() => true), IntPtr.Zero))
                        {
                            using (MemoryStream stream0 = new MemoryStream())
                            {
                                imageNew.Save(stream0, ImageFormat.Jpeg);
                                e.Value = stream0.GetBuffer();
                            }
                        }
                    }
                }
            }
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            var p = list[this.gridView1.GetDataSourceRowIndex(e.RowHandle)];
            var form = Program.MainWindow.MdiChildren.Where(x => x is FormAddProduct).FirstOrDefault() as FormAddProduct;
            if (form != null)
            {
                form.ShowEdit(p);
                form.Activate();
                form.BringToFront();
            }
            else
            {
                form = new FormAddProduct();
                form.MdiParent = Program.MainWindow;
                form.ShowEdit(p);
            }
            
        }
    }
}